import { History } from 'history';
import { fromJS } from 'immutable';
import { routerMiddleware } from 'react-router-redux';
import { applyMiddleware, compose, createStore as createReduxStore } from 'redux';
import createSagaMiddleware from 'redux-saga';
import createReducer from './reducers';

const sagaMiddleware = createSagaMiddleware();

export const createStore = (history: History, initialState = {}) => {
  // 非开发环境的 redux 中间件设置
  const middlewares = [
    sagaMiddleware,
    routerMiddleware(history)
  ];

  // 补充开发环境使用的插件
  const enhancers = [];
  if (__DEV__) {
    const devToolsExtension = window.devToolsExtension;
    if (typeof devToolsExtension === 'function') {
      enhancers.push(devToolsExtension());
    }
  }

  // 创建 store
  const createStoreWithMiddleware = compose(applyMiddleware(...middlewares), ...enhancers);
  const store = createStoreWithMiddleware(createReduxStore)(createReducer({}), fromJS(initialState));

  // Extensions
  store.runSaga = sagaMiddleware.run;
  store.injectedReducers = {}; // Reducer registry
  store.injectedSagas = {}; // Saga registry

  if (module.hot) {
    module.hot.accept('./reducers', () => {
      const rootReducers = require('./reducers').default;
      store.replaceReducer(rootReducers({}));
    });
  }

  return store;
};
